<template>
  <div>
    <h1>{{ store.name }}</h1>
    <p>Count: {{ store.count }}</p>
    <p>Double Count: {{ store.doubleCount }}</p>
    <button @click="store.increment">+1</button>
    <button @click="store.decrement">-1</button>
    <button @click="store.asyncIncrement">Async +1</button>
    <button @click="reset">重置为初始状态</button>
    <button @click="add">添加</button>
    <button @click="del">删除</button>
    <button @click="update">批量修改数据1</button>
    <button @click="update2">批量修改数据2</button>
  </div>
</template>

<script setup>
import { useCounterStore } from '../../stores/counter';
import { getUserInfo, getToken } from '../../utils/api';
import { storeToRefs } from 'pinia';
// 获取store实例
const store = useCounterStore();
// 使用storeToRefs解构state和getters（保留响应式）
const { name, count, doubleCount } = storeToRefs(store);
//  解构actions（无需storeToRefs）
const { increment, decrement } = store;
const add = () => { 
  increment()
}
const del = () => { 
  decrement()
}
console.log(getUserInfo());
console.log(getToken());

// 监听state变化
store.$subscribe((mutation, state) => {
  // mutation 是当前的mutation对象
  // state 是当前的state对象
  // console.log(mutation, state);
})

// 监听action调用
store.$onAction(({ name, store, args, after, onError, afterError }) => {
  // action相关信息
  // name: 当前action的名称
  // store: 当前store实例
  // args: 当前action的参数
  // after: 当前action执行成功后的回调
  // onError: 当前action执行失败时的错误处理
  // afterError: 当前action执行失败后的错误处理
  
  // action执行成功后的回调
  after((result) => {
    console.log(`Action ${name} succeeded with result:`, result);
  });
  
  // action执行失败时的错误处理
  onError((error) => {
    console.log(`Action ${name} failed with error:`, error);
  });
})

// 重置为初始状态
const reset = () => {
  store.$reset();
}

// 批量修改数据
const update = () => {
  store.count += 123;
}

// 批量修改数据2
const update2 = () => {
    store.$patch({
      count: store.count + 10,
      name: 'Updated Name'
    });

    // 或使用函数式$patch
  //  store.$patch((state) => {
  //     state.count += 10;
  //     state.name = 'Updated Name';
  //   });
  }; 
</script>
<style lang="scss" scoped>
button{
  margin-right: 10px;
}
</style>